package com.yxt.common.ui;

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.Properties;

import com.yxt.common.sys.CommUtil;
import com.yxt.exception.DatabaseException;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class HandlerUtil implements UncaughtExceptionHandler {
	/** Debug Log Tag */
	public static final String TAG = "CrashHandler";
	/** 是否开启日志输出, 在Debug状态下开启, 在Release状态下关闭以提升程序性能 */
	public static final boolean DEBUG = true;
	/** CrashHandler实例 */
	private static HandlerUtil INSTANCE;
	/** 程序的Context对象 */
	private Context mContext;
	/** 系统默认的UncaughtException处理类 */
	private Thread.UncaughtExceptionHandler mDefaultHandler;

	/** 使用Properties来保存设备的信息和错误堆栈信息 */
	private Properties mDeviceCrashInfo = new Properties();
	private static final String VERSION_NAME = "versionName";
	private static final String VERSION_CODE = "versionCode";
	private static final String STACK_TRACE = "STACK_TRACE";
	/** 错误报告文件的扩展名 */
	private static final String CRASH_REPORTER_EXTENSION = ".cr";

	/** 保证只有一个CrashHandler实例 */
	private HandlerUtil() {
	}

	/** 获取CrashHandler实例 ,单例模式 */
	public static HandlerUtil getInstance() {
		if (INSTANCE == null)
			INSTANCE = new HandlerUtil();
		return INSTANCE;
	}

	/**
	 * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
	 * @param ctx
	 */
	public void init(Context ctx) {
		mContext = ctx;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	/**
	 * 当UncaughtException发生时会转入该函数来处理
	 */
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			mDefaultHandler.uncaughtException(thread, ex);// 如果用户没有处理则让系统默认的异常处理器来处理
		} else {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				Log.e(TAG, "Error : ", e);
			}
			CommUtil.persistenceAutoLogin(mContext);
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}
	
	private boolean handleException(final Throwable ex) {
		if (ex == null) {
			return true;
		}
		new Thread() {
			public void run() {
				Looper.prepare();
				String msg = "";
				if (ex instanceof DatabaseException) {
					msg = "数据库异常,请与管理员联系";
				} else if (ex instanceof InternetException) {
					msg = "无法连接网络,请确认是否连接网络或者稍候再试";
				} else if (ex instanceof XmlParserException) {
					msg = "解析XML时出错,请与管理员联系";
				} else if (ex instanceof RemoteServerException) {
					msg = ex.getMessage();
				} else {
					msg = "未知错误,请与管理员联系";
				}
				Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
				Looper.loop();
			}
		}.start();
		collectCrashDeviceInfo(mContext);//收集程序崩溃的设备信息
		saveCrashInfoToFile(ex);// 保存错误报告文件
		return true;
	}

	/**
	 * 收集程序崩溃的设备信息
	 * @param ctx
	 */
	public void collectCrashDeviceInfo(Context ctx) {
		try {
			PackageManager pm = ctx.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
					PackageManager.GET_ACTIVITIES);
			if (pi != null) {
				mDeviceCrashInfo.put(VERSION_NAME,
						pi.versionName == null ? "not set" : pi.versionName);
				mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
			}
		} catch (NameNotFoundException e) {
			Log.e(TAG, "Error while collect package info", e);
		}
		
		Field[] fields = Build.class.getDeclaredFields();
		for (Field field : fields) {
			try {
				field.setAccessible(true);
				mDeviceCrashInfo.put(field.getName(), field.get(null));
				if (DEBUG) {
					Log.d(TAG, field.getName() + " : " + field.get(null));
				}
			} catch (Exception e) {
				Log.e(TAG, "Error while collect crash info", e);
			}
		}
	}

	/**
	 * 保存错误信息到文件中
	 * 
	 * @param ex
	 * @return
	 */
	private String saveCrashInfoToFile(Throwable ex) {
		Writer info = new StringWriter();
		PrintWriter printWriter = new PrintWriter(info);
		// 将此 throwable 及其追踪输出到指定的 PrintWriter
		ex.printStackTrace(printWriter);

		// getCause() 返回此 throwable 的 cause；如果 cause 不存在或未知，则返回 null。
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}

		// toString() 以字符串的形式返回该缓冲区的当前值。
		String result = info.toString();
		printWriter.close();
		mDeviceCrashInfo.put(STACK_TRACE, result);
		String fileName = "";
		try {
			long timestamp = System.currentTimeMillis();
			fileName = "crash-" + String.valueOf(timestamp) + CRASH_REPORTER_EXTENSION;
			FileOutputStream trace = mContext.openFileOutput(fileName,Context.MODE_PRIVATE);
			//mDeviceCrashInfo.store(trace, "");
			trace.flush();
			trace.close();
		} catch (Exception e) {
			Log.e(TAG, "an error occured while writing report file...", e);
			return null;
		}
		return fileName;
	}
}